<?php
namespace application\admin\panels;
use application\utilities\Utility;

class manage_users extends panel {
	public $name = 'Manage Users';
	
	public function title() {
		return 'Manage / Users';
	}
	
	public function handleData() {
		if($_REQUEST['perform_bulk_actions']) {
			$users = $_REQUEST['users'];
			if(count($users)) {
			
				$userIn = "'".implode("', '", $users)."'";
				switch($_REQUEST['action']) {
					case 'delete':
						DB()->query("DELETE FROM `cn_users` WHERE `user_id` IN ($userIn)");
						$this->addMessage('success', 'Selected user(s) successfully deleted.');
						break;
					case 'global':
						DB()->query("UPDATE `cn_users` SET `user_level`='2' WHERE `user_id` IN ($userIn)");
						$this->addMessage('success', 'Selected user(s) successfully promoted.');
						break;
					case 'remove-global':
						DB()->query("UPDATE `cn_users` SET `user_level`='0' WHERE `user_id` IN ($userIn)");
						$this->addMessage('success', 'Selected user(s) successfully demoted.');
						break;
					case 'approve':
						if(getOption('user_admin_approval')) {
							foreach($users as $user) {
								$email = DB()->getVar("SELECT `user_email` FROM `cn_users` WHERE `user_id`='$user'");
								$password = Utility::strRand(8);
								DB()->update('cn_users', 'user_id', $user, array('user_password'=>md5($password)));
								$mail = mail($email, 'New Account at ' . CN_SITE_NAME, 'Your account at '.CN_SITE_NAME .' has been approved. You can login by going to '.CN_URL.'login/. Your temporary password is '.$password.'. You can change it when you log in. If you did not create an account, please ignore this e-mail.', 'From: '.CN_SITE_NAME.' Admin  <no-reply@torchdm.com>');
							}
						}
						DB()->query("UPDATE `cn_users` SET `user_level`='0' WHERE `user_id` IN ($userIn)");
						break;
				}
					
			}
		}
		$this->display();
	}
	
	public function sidebar() {
		$contentType = $_REQUEST['type'];
		?>
			
			<form id="filter" class="inner" method="get">
				<input type="hidden" name="display" value="<?=getQueryVar('display')?>"/>
				<ul id="filter-content">
				<li><label for="level">User Level</label>
					<select name="level">
						<option <?=(getQueryVar('level') == 'all') ? 'selected="selected"' : ''?> value="all">All (<?=DB()->getCount("SELECT `user_id` FROM `cn_users`");?>)</option>
						<option <?=(getQueryVar('level') == 'global_admin') ? 'selected="selected"' : ''?> value="global_admin">Global Administrator (<?=DB()->getCount("SELECT `user_id` FROM `cn_users` WHERE `user_level`='2'");?>)</option>
						<option <?=(getQueryVar('level') == 'local_admin') ? 'selected="selected"' : ''?> value="local_admin">Local Administrator (<?=DB()->getCount("SELECT `user_id` FROM `cn_users` WHERE `user_level`='1'");?>)</option>
						<option <?=(getQueryVar('level') == 'normal') ? 'selected="selected"' : ''?> value="normal">Normal (<?=DB()->getCount("SELECT `user_id` FROM `cn_users` WHERE `user_level`='0' || `user_level`=NULL");?>)</option>
						<option <?=(getQueryVar('level') == 'pending') ? 'selected="selected"' : ''?> value="pending">Pending (<?=DB()->getCount("SELECT `user_id` FROM `cn_users` WHERE `user_level`='-1'");?>)</option>
					</select>
				</li>
				<li><label>Order by</label>
				<select name="order">
					<option <?=(getQueryVar('order') == 'username') ? ' selected="selected"' : '';?> value="username">Username</option>
					<option <?=(getQueryVar('order') == 'email') ? ' selected="selected"' : '';?> value="email">E-Mail</option>
					<option <?=(getQueryVar('order') == 'id') ? ' selected="selected"' : '';?> value="id">ID</option>
				</select>
				</li>
				<li>
					<label for="search">Search</label>
					<input type="text" name="search" value="<?=getQueryVar('search')?>"/>
				</li>
				<li>
					<h5>Show Fields</h5>
					<?php $fields = DB()->getResults("SELECT * FROM `cn_content_fields` WHERE `cf_content_type`='0' ORDER BY `cf_display_name`");
					foreach($fields as $field) : ?>
					<?php if($field->cf_data_type != 'Password') : ?>
					<label><input <?php if($field->cf_show) echo 'checked="checked"';?> type="checkbox" name="fields[]" value="<?=$field->cf_id?>"/> <?=$field->cf_display_name?></label>
					<?php endif; endforeach;?>
				</li>
				<li>
					<input type="submit" value="Filter" id="filter-submit" name="filter_content" class="small-button"/>
				</li>
			</ul>
			</form>
			<form method="get" class="inner">
			
				<select id="action-to-take" name="bulk_actions">
					<option value="">Bulk Actions</option>
					<option value="delete">Delete Selected</option>
					<option value="global">Make Global Administrators</option>
					<option value="remove-global">Remove Global Administrators</option>
					<option value="approve">Approve Pending User Accounts</option>
				</select>
				<input type="submit" class="small-button" value="Go" id="perform-bulk-actions" name="perform_bulk_actions"/>
			</form>
			<script type="text/javascript">
			$('#filter').submit(function(e) {
				e.preventDefault();
				var values = $(this).serialize();
				$.ajax({
					url:concerto.admin.rootUrl + 'admin/?mode=ajax-content&' + values,
					beforeSend:function() {
						$('#main').fadeOut(200);
					},
					success:function(response) {
						$('.torchd-ui-ajax-loader').remove();
						$('#main').html(response).fadeIn(100);
					}
				});

			});
			$('#perform-bulk-actions').click(function(e) {
				e.preventDefault();
				
				// Get all selected users
				var users = [];
				$('table.admin-table tbody').find('input[type="checkbox"]').each(function() {
					if($(this).attr('checked')) {
						users.push($(this).val());
					}
				});
				var action = $('#action-to-take').val();
				if(action) {
					if(action == 'delete') {
						torchd.ui.showDialog({
							type:'confirm',
							title:'Delete users?',
							message:'Are you sure you want to delete these users?',
							onSubmit:function() {
								$.ajax({
									url:concerto.admin.rootUrl + 'admin?mode=handle-data&display=manage_users',
									type:'POST',
									data:{
										perform_bulk_actions:1,
										action:action,
										users:users
									},
									beforeSend:function() {
										torchd.ui.showDialog({
											title:'Performing actions...',
											type:'ajax-loader'
										});
									},
									success:function(response) {
										torchd.ui.closeAllDialogs();
										$('#main').html(response);
									}
								});
							}
						});
					}
					else {
						$.ajax({
							url:concerto.admin.rootUrl + 'admin?mode=handle-data&display=manage_users',
							type:'POST',
							data:{
								perform_bulk_actions:1,
								action:action,
								users:users
							},
							beforeSend:function() {
								torchd.ui.showDialog({
									title:'Performing actions...',
									type:'ajax-loader'
								});
							},
							success:function(response) {
								torchd.ui.closeAllDialogs();
								$('#main').html(response);
							}
						});
					
					}
				}
			});
			</script>
			<?php
	}
	
	public function display() {
		global $concerto;
		$contentType = $_REQUEST['type'];
		if(!getQueryVar('limit')) {
			setQueryVar('limit', 20);
		}
		if($_REQUEST['fields']) {
			// Check/uncheck shown fields
			DB()->query("UPDATE `cn_content_fields` SET `cf_show`='0' WHERE `cf_content_type`='0'");
			DB()->query("UPDATE `cn_content_fields` SET `cf_show`='1' WHERE `cf_content_type`='0' AND `cf_id` IN ('".implode("', '", $_REQUEST['fields'])."')");
		}

		$concerto->UsersQuery->initMainQuery();
		
		$shownColumns = DB()->getVarArray("SELECT `cf_display_name` FROM `cn_content_fields` WHERE `cf_content_type`='0' AND `cf_show`='1'");
		
		?>
		<div class="box">
			
			<h3>Manage <b>Users</b></h3>
			
			<table class="admin-table" width="100%">
				<thead>
					<tr>
						<th class="first" width="2%"><input type="checkbox" class="select-all"/></th>
						
						<?php foreach($shownColumns as $column) : ?>
						<th><?=$column?></th>
						<?php endforeach;?>
						<th width="15%">Actions</th>
						<th class="last" width="2%"></th>
					</tr>
				</thead>
				<tfoot>
					<tr>
						<th class="first" width="2%"><input type="checkbox" class="select-all"/></th>
						<?php foreach($shownColumns as $column) : ?>
						<th><?=$column?></th>
						<?php endforeach;?>
						<th width="15%">Actions</th>
						<th class="last" width="2%"></th>
					</tr>
				</tfoot>
				<tbody>
					
					<?php $style = ''; 
					while(hasUsers()) : initUser();?>
					<tr<?=$style?>>
						<td><input type="checkbox" name="contents[]" value="<?php displayUserField('ID');?>" class="selectee-all"/></td>				
						<?php foreach($shownColumns as $value) : ?>
						<td><?php displayUserField($value);?></td>
						<?php endforeach;?>
						<td><a target="_blank" href="<?=CN_URL?>?view=form&form=edit_profile&id=<?=getUserField('ID')?>" href="">Edit</a></td>
						<td></td>
					</tr>
					<?php $style = ($style == ' class="alternate"') ? '' : ' class="alternate"';?>
					<?php endwhile;?>
				</tbody>
			</table>
		</div>
		
		<?php
	}
}
?>